package com.example.happiness.task;
import com.example.happiness.constant.Message;
import com.example.happiness.mapper.OrderMapper;
import com.example.happiness.pojo.Order;
import com.example.happiness.pojo.generalDTO.OrderStateDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeOutOrder(){
        log.info("定时处理服务结束订单和自动接单：{}", LocalDateTime.now());
        List<Order> orders = orderMapper.getOrderList();
        if(orders != null && orders.size()>0){
            for (Order order : orders) {
                if(Objects.equals(order.getState(), Message.NINE)){
                    OrderStateDTO orderStateDTO = new OrderStateDTO();
                    orderStateDTO.setOrderid(order.getOrderid());
                    orderStateDTO.setState(Message.FIVE);
                    orderMapper.updataOrderState(orderStateDTO);
                }else if(Objects.equals(order.getState(), Message.TWO)){
                    Duration duration = Duration.between(LocalDateTime.now(),order.getOrderdate());
                    long hours = duration.toHours();
                    if (hours <= 24){
                        OrderStateDTO orderStateDTO = new OrderStateDTO();
                        orderStateDTO.setOrderid(order.getOrderid());
                        orderStateDTO.setState(Message.SEVEN);
                        orderMapper.updataOrderState(orderStateDTO);
                    }
                }
            }
        }
    }
    @Scheduled(cron = "0 * * * * ? ")
    public void deleteTimeOutOrder(){
        log.info("定时处理未支付订单：{}", LocalDateTime.now());
        List<Order> orders = orderMapper.getOrderList();
        if(orders != null && orders.size()>0){
            for (Order order : orders) {
                if(Objects.equals(order.getState(), Message.ONE)){
                    orderMapper.deleteByPrimaryKey(order.getOrderid());
                }
            }
        }
    }
}
